﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp7
{
    /// <summary>
    /// 继承自IObserver,可认为是一个订阅消息发送器，可处理来自Location类型的通知
    /// </summary>
    public class LocationReporter : IObserver<Location>
    {
        private IDisposable unsubscriber;
        private string instName;

        //注销订阅
        public virtual void Unsubscribe()
        {
            unsubscriber.Dispose();
        }


        public LocationReporter(string name)
        {
            this.instName = name;
        }
        public string Name
        { get { return this.instName; } }

        public virtual void Subscribe(IObservable<Location> provider)
        {
            if (provider != null)
                unsubscriber = provider.Subscribe(this);
        }


        //订阅完成时处理逻辑
        public void OnCompleted()
        {
            Console.WriteLine("The Location Tracker has completed transmitting data to {0}.", this.Name);
            this.Unsubscribe();
        }

        //出错时处理逻辑
        public void OnError(Exception error)
        {
            Console.WriteLine("{0}: The location cannot be determined.", this.Name);
            //throw new NotImplementedException();
        }

        //接收到通知处理什么
        public void OnNext(Location value)
        {
            Console.WriteLine("{2}: The current location is {0}, {1}", value.Latitude, value.Longitude, this.Name);
            //throw new NotImplementedException();
        }
    }
}
